package com.epalmpay.service.weixin.impl;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.epalmpay.entity.Agent;
import com.epalmpay.entity.Group;
import com.epalmpay.entity.Member;
import com.epalmpay.entity.Shop;
import com.epalmpay.entity.ShopGroupRelation;
import com.epalmpay.entity.Wallet;
import com.epalmpay.entity.WalletInfo;
import com.epalmpay.exception.ApplicationException;
import com.epalmpay.mapper.AgentMapper;
import com.epalmpay.mapper.GroupMapper;
import com.epalmpay.mapper.MemberMapper;
import com.epalmpay.mapper.ShopGroupRelationMapper;
import com.epalmpay.mapper.ShopMapper;
import com.epalmpay.mapper.WalletInfoMapper;
import com.epalmpay.mapper.WalletMapper;
import com.epalmpay.payplat.IPayAPI;
import com.epalmpay.payplat.MerchantWithsDraw;
import com.epalmpay.payplat.PayBalanceChange;
import com.epalmpay.payplat.PayBalanceQuery;
import com.epalmpay.payplat.PayConsumption;
import com.epalmpay.payplat.PayTransfer;
import com.epalmpay.payplat.PayWithdrawalBank;
import com.epalmpay.payplat.PayWxPaymentRecharge;
import com.epalmpay.payplat.UnPayConsumption;
import com.epalmpay.payplat.WarrantDrawRequest;
import com.epalmpay.payplat.result.PayBalanceResult;
import com.epalmpay.payplat.result.PayResult;
import com.epalmpay.payplat.result.PayTransferResult;
import com.epalmpay.payplat.result.PayWithdrawalResult;
import com.epalmpay.payplat.result.PayWxPayResult;
import com.epalmpay.service.weixin.IWalletService;
import com.epalmpay.status.Rescode;
import com.epalmpay.util.DateUtil;
import com.epalmpay.util.Response;
import com.epalmpay.util.StringUtil;
import com.epalmpay.util.payplat.DateUtils;
import com.epalmpay.util.payplat.UtilFun;

@Service("walletService")
public class WalletServiceImpl implements IWalletService {
	
	
	@Resource
	private WalletMapper walletMapper;
	@Resource
	private WalletInfoMapper walletInfoMapper;
	@Resource
	private MemberMapper memberMapper;
	@Resource
	private AgentMapper agentMapper;
	@Resource
	private GroupMapper groupMapper;
	@Resource
	private ShopMapper shopMapper;
	@Resource
	private ShopGroupRelationMapper shopGroupRelationMapper;
	
	
	
	private static Logger logger = LoggerFactory.getLogger(WalletServiceImpl.class);
	
	/**
	 * 
	 * @param tranAmt 交易金额
	 * @param isWithdraw  是否可提现  1可提现   0 不可提现
	 * @param day   锁定时间
	 * @param virtualCard  支付平台用户id
	 * @param payGroupCode 支付平台商户号
	 * @param userId       2.0用户id
	 * @return
	 * @throws ApplicationException
	 */
	public Boolean balanceLocked(String tranAmt, String isWithdraw,Integer day,String virtualCard,String payGroupCode,Long userId,String orderId)
			throws ApplicationException{
		Wallet wallet=walletMapper.selectByUserId(userId);
		Date date=new Date();
		if(wallet==null){
				PayBalanceResult payResult =getBalance(virtualCard, payGroupCode,false);
				Wallet walletDto=new Wallet();
				WalletInfo walletInfo=new WalletInfo();
				walletDto.setUserId(userId);
			if(day>0){ //进行锁定金额
						switch (isWithdraw) {
						case "1"://可提现
							walletDto.setCanBalanceLocked(Integer.valueOf(tranAmt));
							walletDto.setNocanBalanceLocked(0);
							
							walletInfo.setCanAmount(Integer.valueOf(tranAmt));
							walletInfo.setNocanAmount(0);
							break;
						case "0"://不可提现
							walletDto.setCanBalanceLocked(0);
							walletDto.setNocanBalanceLocked(Integer.valueOf(tranAmt));
							
							walletInfo.setNocanAmount(Integer.valueOf(tranAmt));
							walletInfo.setCanAmount(0);
							break;
						}
						walletDto.setCanBalance(Integer.parseInt(payResult.getCurBal()));//可提现金额为 系统变化之前的余额
						walletDto.setNocanBalance(Integer.parseInt(payResult.getCurBalB()));//不可提现金额   系统变化之前的余额
						
						walletDto.setCanFreezeBalance(Integer.parseInt(payResult.getLockBal()));//支付平台可提现锁定金额
						walletDto.setNocanFreezeBalance(Integer.parseInt(payResult.getLockBalB()));//支付平台不可提现锁定金额
						
						walletInfo.setGmtEnd(DateUtil.getTimeOf0(day));//截止时间 
						walletInfo.setVerify(0);//标记为未结算
				}else{
					//不进行锁定金额
				  logger.info("+========不进行锁定金额支付平台可提现锁定金额CanFreezeBalance========"+Integer.parseInt(payResult.getLockBal()));
				  logger.info("+========不进行锁定金额支付平台不可提现锁定金额NocanFreezeBalance========"+Integer.parseInt(payResult.getLockBalB()));
					walletDto.setCanFreezeBalance(Integer.parseInt(payResult.getLockBal()));//支付平台可提现锁定金额
					walletDto.setNocanFreezeBalance(Integer.parseInt(payResult.getLockBalB()));//支付平台不可提现锁定金额
					
					walletDto.setNocanBalanceLocked(0);
					walletDto.setCanBalanceLocked(0);
					
						switch (isWithdraw) {
						case "1":
							logger.info("CanBalance"+Integer.parseInt(payResult.getCurBal())+Integer.valueOf(tranAmt));
							logger.info("NocanBalance"+Integer.parseInt(payResult.getCurBalB()));
							walletDto.setCanBalance(Integer.parseInt(payResult.getCurBal())+Integer.valueOf(tranAmt));
							walletDto.setNocanBalance(Integer.parseInt(payResult.getCurBalB()));
							
							walletInfo.setCanAmount(Integer.valueOf(tranAmt));
							walletInfo.setNocanAmount(0);
							break;
						case "0":
							logger.info("CanBalance"+Integer.parseInt(payResult.getCurBalB()));
							logger.info("NocanBalance"+Integer.parseInt(payResult.getCurBalB())+Integer.valueOf(tranAmt));
							walletDto.setCanBalance(Integer.parseInt(payResult.getCurBal()));//可提现金额
							walletDto.setNocanBalance(Integer.parseInt(payResult.getCurBalB())+Integer.valueOf(tranAmt));//不可提现金额
							
							walletInfo.setCanAmount(0);
							walletInfo.setNocanAmount(Integer.valueOf(tranAmt));
							break;
						}
						walletInfo.setGmtEnd(date);
						walletInfo.setVerify(1);//标记为结算
				}
				logger.info("+========本地不存在时候去更新钱包信息========");
				walletInfo.setGmtCreate(date);
				walletInfo.setUserId(userId);
				walletMapper.insertSelective(walletDto);
				walletInfo.setWalletId(walletDto.getId());
				walletInfo.setOrderId(orderId);
				walletInfoMapper.insertSelective(walletInfo);
				
		}else{
			
			WalletInfo walletInfo=new WalletInfo();
				if(day>0){
					switch (isWithdraw) {
					case "1":
						//锁定金额累计
						Integer canBalanceLocked=wallet.getCanBalanceLocked()+Integer.valueOf(tranAmt);
						wallet.setCanBalanceLocked(canBalanceLocked);
						
						walletInfo.setCanAmount(Integer.valueOf(tranAmt));
						walletInfo.setNocanAmount(0);
						break;
					case "0":
						Integer nocanBalanceLocked=wallet.getNocanBalance()+Integer.valueOf(tranAmt);
						wallet.setNocanBalanceLocked(nocanBalanceLocked);
						
						walletInfo.setCanAmount(0);
						walletInfo.setNocanAmount(Integer.valueOf(tranAmt));
						break;
					}
					walletInfo.setGmtEnd(DateUtil.getTimeOf0(day));//截止时间 
					walletInfo.setVerify(0);//标记为未结算
			}else{
				//时间为0
					switch (isWithdraw) {
					case "1":
						logger.info("==可提现CanAmount======"+Integer.valueOf(tranAmt));
						logger.info("==不可提现NocanAmount======"+0);
						walletInfo.setCanAmount(Integer.valueOf(tranAmt));
						walletInfo.setNocanAmount(0);
						//可提现金额直接累加
						Integer canBalance=wallet.getCanBalance()+Integer.valueOf(tranAmt);
						logger.info("==canBalance======"+canBalance);
						wallet.setCanBalance(canBalance);
						break;
					case "0":

						logger.info("==CanAmoun======"+0);
						logger.info("==nocanAmount======"+Integer.valueOf(tranAmt));

						walletInfo.setCanAmount(0);
						walletInfo.setNocanAmount(Integer.valueOf(tranAmt));
						
						//不可提现金额直接累加
						Integer nocanBalance=wallet.getNocanBalance()+Integer.valueOf(tranAmt);
						wallet.setNocanBalance(nocanBalance);//不可提现金额
						logger.info("==nocanBalance======"+nocanBalance);

						break;
					}
					walletInfo.setGmtEnd(date);
					walletInfo.setVerify(1);//标记为已结算
			}
			walletInfo.setGmtCreate(date);
			walletInfo.setUserId(userId);
			walletInfo.setWalletId(wallet.getId());
			logger.info("==钱包更新======");
			walletMapper.updateByPrimaryKeySelective(wallet);
			walletInfo.setOrderId(orderId);
			walletInfoMapper.insertSelective(walletInfo);
		}
		return true;
	}
	
	

	@Override
	public Response updateLockedAmount(String id,String type,String tranAmt, String isWithdraw,Integer day,String orderId) throws ApplicationException {
		//type 类型判断用户类型
		Long userId=null;
		String virtualCard=null;
		String payGroupCode=null;
		switch (type) {
		case "1":
			logger.info("==========推荐人id"+id);
			Member member1 = memberMapper.queryGroup(Long.parseLong(id));
			if(member1==null){
				return Response.getError("会员信息不存在");
			}
			userId=member1.getUserId();
			virtualCard=member1.getVirtualCard();
			payGroupCode=member1.getPayGroupCode();
			break;
		case "2":
			Agent agent=agentMapper.selectByPrimaryKey(Long.parseLong(id));
			if(agent==null){
				return Response.getError("代理商信息不存在");
			}
			userId=agent.getUserId();
			virtualCard=agent.getPacketNum();
			Group group=groupMapper.selectByPrimaryKey(agent.getGroupId());
			payGroupCode=group.getPayGroupCode();
			break;
		default:
			Shop shop=shopMapper.selectByPrimaryKey(Long.parseLong(id));
			if(shop==null){
				return Response.getError("门店信息不存在");
			}
			ShopGroupRelation shopGroupRelation=shopGroupRelationMapper.selectByShopId(shop.getId());
			if(shopGroupRelation==null){
				return Response.getError("门店信息不存在");
			}
			Group group2=groupMapper.selectByPrimaryKey(shopGroupRelation.getGroupId());
			userId=shop.getUserId();
			virtualCard=shopGroupRelation.getPayMerchantCode();
			payGroupCode=group2.getPayGroupCode();
			logger.info("------------virtualCard--------------"+virtualCard);
			logger.info("------------payGroupCode--------------"+payGroupCode);

			break;
		}
		logger.info("==================type: "+type);
		logger.info("首次消费去更新本地钱包信息");
		logger.info("==================payGroupCode"+payGroupCode);
		logger.info("==================virtualCard"+virtualCard);
		logger.info("==================tranAmt: "+tranAmt);
		logger.info("==================isWithdraw: "+isWithdraw);
		logger.info("==================userId: "+userId);
		logger.info("==================orderId: "+orderId);

		 Boolean flag=balanceLocked(tranAmt, isWithdraw, day, virtualCard, payGroupCode, userId,orderId);

		logger.info("首次消费去支付平台钱包信息");
		 //只有门店和会员用户加余额
		 if(type.equals("1")|| type.equals("2")){
			 logger.info("++++++++++++++++++++++"+flag);
			 if(flag){

				 //最后增加或者减少余额变化
				 logger.info("==================payGroupCode: "+payGroupCode);
				 logger.info("==================virtualCard: "+virtualCard);
				 logger.info("==================tranAmt: "+tranAmt);
				 logger.info("==================isWithdraw: "+isWithdraw);
				 logger.info("==================data: "+DateUtils.getDateTimeString("yyyyMMddHHmmss"));
				 PayResult payResult=accountBalance(payGroupCode,virtualCard, tranAmt, isWithdraw, DateUtils.getDateTimeString("yyyyMMddHHmmss"));
				 if (!payResult.getRespCode().equals("0000")) {
						throw new ApplicationException(Rescode.FAIL, payResult.getMsgTxt());
				 }
				 logger.info("gengxin支付平台钱包chengg");
			 }
		 }
		 
		Map<String, Object> resultMap = new HashMap<String, Object>();
		resultMap.put("tranAmt", tranAmt);
		return Response.getSuccess(resultMap);
	} 
	
	
	 
	@Override
	public PayResult updateUserLockedAmount(String virtualCard,String payGroupCode,Long userId,String tranAmt,String isWithdraw,Integer day,String orderId) throws ApplicationException{
		Boolean flag=balanceLocked(tranAmt, isWithdraw, day, virtualCard, payGroupCode, userId,orderId);
		logger.info("=================标志=================="+flag);
		if(flag){
			//最后增加或者减少余额变化
			logger.info("=================给支付平台交易余额==================");
			logger.info("=================GroupId=================="+payGroupCode);
			PayResult payResult=accountBalance(payGroupCode,virtualCard, tranAmt, isWithdraw, DateUtils.getDateTimeString("yyyyMMddHHmmss"));
			return payResult;
		 }
		return null;
	} 
	
	
	@Override
	public PayWxPayResult updateRecharge(String virtualCard,String payGroupCode,Long userId,String OrgOrderNum, String tranAmt,
			String mchCreateIp, String wxAppid, String openid,String isWithdraw)
			throws ApplicationException {
		Wallet wallet=walletMapper.selectByUserId(userId);
		if(wallet==null){
			PayBalanceResult payResult =getBalance(virtualCard, payGroupCode,false);
			Wallet walletDto=new Wallet();
			walletDto.setCanBalance(Integer.parseInt(payResult.getCurBal()));//可提现金额为 系统变化之前的余额
			walletDto.setNocanBalance(Integer.parseInt(payResult.getCurBalB()));//不可提现金额   系统变化之前的余额
			walletDto.setCanBalanceLocked(0);
			walletDto.setNocanBalanceLocked(0);
			walletDto.setUserId(userId);
			walletDto.setCanFreezeBalance(Integer.parseInt(payResult.getLockBal()));//支付平台可提现锁定金额
			walletDto.setNocanFreezeBalance(Integer.parseInt(payResult.getLockBalB()));//支付平台不可提现锁定金额
			
		}
			PayWxPaymentRecharge payWxPaymentRecharge = PayWxPaymentRecharge.initialize(payGroupCode, virtualCard, OrgOrderNum,
					tranAmt, "156", DateUtil.fomatDate(new Date(), DateUtil.sdfTimes), DateUtil.fomatDate(new Date(), DateUtil.sdfTimes), "用户钱包充值", mchCreateIp, wxAppid,
			openid, null, isWithdraw);
			PayWxPayResult payResult = IPayAPI.userWxPaymentRecharge(payWxPaymentRecharge);
			if (!payResult.getRespCode().equals("0000")) {
				throw new ApplicationException(Rescode.FAIL, payResult.getMsgExt());
			}
			return payResult;
	}
	
	
	/**
	 * 余额查询
	 * @param virtualCard  用户编号
	 * @param payGroupCode 机构号
	 * @return
	 * @throws ApplicationException
	 */
	public static PayBalanceResult  getBalance(String virtualCard,String payGroupCode,boolean isMerchant) throws ApplicationException{
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
		String str = simpleDateFormat.format(new Date());
		String orgTranDateTime = str;
		String SysTraceNum = StringUtil.getRandNumberStr(12);// 交易流水号12位
		PayBalanceQuery payBalanceQuery = PayBalanceQuery.initialize(virtualCard, payGroupCode, SysTraceNum, orgTranDateTime, UtilFun.createOrderNum());
		PayBalanceResult payResult = IPayAPI.accountBalanceQuery(payBalanceQuery, isMerchant);
		if (!PayBalanceResult.SUCCESS.equals(payResult.getRespCode())) {
			logger.info (payResult.getMsgTxt()); 
			throw new ApplicationException(payResult.getMsgTxt());
    	}
		return payResult;
	}
	
	/**
	 * 余额变动
	 * @param payGroupCode
	 * @param virtualCard
	 * @param tranAmt  是否可提现 0不可提现 1可提现
	 * @param isWithdraw  
	 * @param orgOrderNum
	 * @return
	 * @throws ApplicationException
	 */
	public static PayResult  accountBalance(String payGroupCode,String virtualCard,String tranAmt,String isWithdraw,String orgOrderNum) throws ApplicationException{
		 PayBalanceChange payBalanceChange = PayBalanceChange.initialize(payGroupCode, virtualCard, tranAmt,
					isWithdraw, UtilFun.createOrderNum(), orgOrderNum, UtilFun.createRandomNum(10), "156");
				PayResult payBalanceChangeResult = IPayAPI.consumptionBalanceChange(payBalanceChange);
				return payBalanceChangeResult;
	}



	@Override
	public Wallet selectwallet(String virtualCard, String payGroupCode, Long userId) throws ApplicationException {
		Wallet wallet=walletMapper.selectByUserId(userId);
		if(wallet==null){
			PayBalanceResult payResult =getBalance(virtualCard, payGroupCode,false);
			Wallet record=new Wallet();
			record.setCanBalance(Integer.parseInt(payResult.getCurBal()));
			record.setNocanBalance(Integer.parseInt(payResult.getCurBalB()));
			record.setCanBalanceLocked(0);
			record.setNocanBalanceLocked(0);
			record.setUserId(userId);
			record.setCanFreezeBalance(Integer.parseInt(payResult.getLockBal()));//支付平台可提现锁定金额
			record.setNocanFreezeBalance(Integer.parseInt(payResult.getLockBalB()));//支付平台不可提现锁定金额
			walletMapper.insertSelective(record);
			return record;

		}else{
			return wallet;
		}
		
	}



	@Override
	public Wallet selectShopWallet(String virtualCard, String payGroupCode, Long userId) throws ApplicationException {
		Wallet wallet=walletMapper.selectByUserId(userId);
		if(wallet==null){
			PayBalanceResult payResult =getBalance(virtualCard, payGroupCode,true);
			Wallet record=new Wallet();
			record.setCanBalance(Integer.parseInt(payResult.getCurBal()));
			record.setNocanBalance(Integer.parseInt(payResult.getCurBalB()));
			record.setCanBalanceLocked(0);
			record.setNocanBalanceLocked(0);
			record.setUserId(userId);
			record.setCanFreezeBalance(Integer.parseInt(payResult.getLockBal()));//支付平台可提现锁定金额
			record.setNocanFreezeBalance(Integer.parseInt(payResult.getLockBalB()));//支付平台不可提现锁定金额
			walletMapper.insertSelective(record);
			return record;
		}else{
			return wallet;
		}
	}



	@Override
	public PayResult updatePayConsumption(String virtualCard, String payGroupCode, Long userId, 
			Integer tranAmt,String orgOrderNum,String payPwd,String MerchantId,String orderId)
			throws ApplicationException { 
		
		logger.info ("==================================用户id:"+userId);
		
		Wallet wallet=walletMapper.selectByUserId(userId);
		Date date=new Date();
		if(wallet==null){
			logger.info ("==================================wallet为空");
			//查询余额
			PayBalanceResult payResult =getBalance(virtualCard, payGroupCode,false);
			Integer curBalA=Integer.valueOf(payResult.getCurBal());
			Integer curBalB=Integer.valueOf(payResult.getCurBalB());
			if(curBalB>=tranAmt){
				    logger.info ("直接扣B卡金额"); 
					Wallet walletDto=new Wallet();
					walletDto.setCanBalance(curBalA);
					walletDto.setCanBalanceLocked(0);
					walletDto.setNocanBalance(curBalB-tranAmt);
					walletDto.setNocanBalanceLocked(0);
					walletDto.setUserId(userId);
					walletDto.setCanFreezeBalance(Integer.parseInt(payResult.getLockBal()));//支付平台可提现锁定金额
					walletDto.setNocanFreezeBalance(Integer.parseInt(payResult.getLockBalB()));//支付平台不可提现锁定金额
					walletMapper.insertSelective(walletDto);
					
					WalletInfo walletInfo=new WalletInfo();
					walletInfo.setCanAmount(0);
					walletInfo.setNocanAmount(-tranAmt);
					walletInfo.setGmtCreate(date);
					walletInfo.setGmtEnd(date); 
					walletInfo.setUserId(userId);
					walletInfo.setVerify(1);//标记为结算
					walletInfo.setWalletId(walletDto.getId());
					walletInfo.setOrderId(orderId);
					walletInfoMapper.insertSelective(walletInfo);
						
					
			}else{
				switch (curBalB) {
				case 0: 
					logger.info ("B卡金额为0  直接扣A卡金额"); 
					Wallet walletDto=new Wallet();
					walletDto.setCanBalance(curBalA-tranAmt);
					walletDto.setCanBalanceLocked(0);
					walletDto.setNocanBalance(0);
					walletDto.setNocanBalanceLocked(0);
					walletDto.setUserId(userId);
					walletDto.setCanFreezeBalance(Integer.parseInt(payResult.getLockBal()));//支付平台可提现锁定金额
					walletDto.setNocanFreezeBalance(Integer.parseInt(payResult.getLockBalB()));//支付平台不可提现锁定金额
					walletMapper.insertSelective(walletDto);
					
					WalletInfo walletInfo=new WalletInfo();
					walletInfo.setCanAmount(-tranAmt);
					walletInfo.setNocanAmount(0);
					walletInfo.setGmtCreate(date);
					walletInfo.setGmtEnd(date); 
					walletInfo.setUserId(userId);
					walletInfo.setVerify(1);//标记为结算
					walletInfo.setWalletId(walletDto.getId());
					walletInfo.setOrderId(orderId);
					walletInfoMapper.insertSelective(walletInfo);
					
					break;
				default:
					logger.info ("扣完B卡金额 继续扣A卡金额"); 
					Wallet walletAB=new Wallet();
					// 交易20  b卡10
//					walletAB.setCanBalance(curBalA+curBalB-tranAmt);
					walletAB.setCanBalance(curBalA-tranAmt+curBalB);
					walletAB.setCanBalanceLocked(0);
					walletAB.setNocanBalance(0);
					walletAB.setNocanBalanceLocked(0);
					walletAB.setUserId(userId);
					walletAB.setCanFreezeBalance(Integer.parseInt(payResult.getLockBal()));//支付平台可提现锁定金额
					walletAB.setNocanFreezeBalance(Integer.parseInt(payResult.getLockBalB()));//支付平台不可提现锁定金额
					walletMapper.insertSelective(walletAB);
					
					WalletInfo walletInfoAB=new WalletInfo();
					walletInfoAB.setCanAmount(-(tranAmt-curBalB));// 消费金额=消费金额-B卡金额
					walletInfoAB.setNocanAmount(-curBalB);
					walletInfoAB.setGmtCreate(date);
					walletInfoAB.setGmtEnd(date); 
					walletInfoAB.setUserId(userId);
					walletInfoAB.setVerify(1);//标记为结算
					walletInfoAB.setWalletId(walletAB.getId());
					walletInfoAB.setOrderId(orderId);
					walletInfoMapper.insertSelective(walletInfoAB);
					
					break;
				}
				
			}
			
		}else{
			logger.info ("==================================wallet不为空");
					if(wallet.getNocanBalance()>=tranAmt){//
						logger.info ("直接扣B卡金额"); 
						wallet.setNocanBalance(wallet.getNocanBalance()-tranAmt);
						walletMapper.updateByPrimaryKeySelective(wallet);
						
						WalletInfo walletInfo=new WalletInfo();
						walletInfo.setCanAmount(0);
						walletInfo.setNocanAmount(-tranAmt);
						walletInfo.setGmtCreate(date);
						walletInfo.setGmtEnd(date); 
						walletInfo.setUserId(userId);
						walletInfo.setVerify(1);//标记为结算
						walletInfo.setWalletId(wallet.getId());
						walletInfo.setOrderId(orderId);
						walletInfoMapper.insertSelective(walletInfo);
							
						
					}else{
						//B卡余额不足消费
						switch (wallet.getNocanBalance()) {
						case 0: 
							logger.info ("B卡金额为0  直接扣A卡金额"); 
							Integer Balance1=wallet.getCanBalance();
							logger.info ("=====A卡余额======="+Balance1);
							logger.info ("======交易金额======"+tranAmt);
							wallet.setCanBalance(Balance1-tranAmt);
							walletMapper.updateByPrimaryKeySelective(wallet);
							WalletInfo walletInfo=new WalletInfo();
							walletInfo.setCanAmount(-tranAmt);
							walletInfo.setNocanAmount(0);
							walletInfo.setGmtCreate(date);
							walletInfo.setGmtEnd(date); 
							walletInfo.setUserId(userId);
							walletInfo.setVerify(1);//标记为结算
							walletInfo.setWalletId(wallet.getId());
							walletInfo.setOrderId(orderId);
							walletInfoMapper.insertSelective(walletInfo);
							
							break;
						default:
							logger.info ("扣完B卡金额 继续扣A卡金额");


							Integer BalanceA=wallet.getCanBalance();
							Integer BalanceB=wallet.getNocanBalance();
							logger.info ("=====A卡余额======="+BalanceA);
							logger.info ("======B卡余额======"+BalanceB);
							logger.info ("======交易金额======"+tranAmt);

							// 交易20  b卡10
//							wallet.setCanBalance(BalanceA+BalanceB-tranAmt);
							wallet.setCanBalance(BalanceA-tranAmt+BalanceB);


							wallet.setNocanBalance(0);
							WalletInfo walletInfoAB=new WalletInfo();
							walletInfoAB.setCanAmount(-(tranAmt-BalanceB));// 消费金额=消费金额-B卡金额
							walletInfoAB.setNocanAmount(-BalanceB);
							walletInfoAB.setGmtCreate(date);
							walletInfoAB.setGmtEnd(date); 
							walletInfoAB.setUserId(userId);
							walletInfoAB.setVerify(1);//标记为结算
							walletInfoAB.setWalletId(wallet.getId());
							walletMapper.updateByPrimaryKeySelective(wallet);
							walletInfoAB.setOrderId(orderId);
							walletInfoMapper.insertSelective(walletInfoAB);
							break;
						}
				}
			
		}

		logger.info("=====================virtualCard"+virtualCard);
		logger.info("=====================payPwd"+payPwd);
		logger.info("=====================orgOrderNum"+orgOrderNum);
		logger.info("=====================payGroupCode"+payGroupCode);
		logger.info("=====================data"+DateUtil.fomatDate(new Date(), DateUtil.sdfTimes));
		logger.info("=====================orgOrderNum"+orgOrderNum);
		logger.info("=====================tranAmt"+tranAmt);
		logger.info("=====================币种"+156);
		logger.info("=====================MerchantId"+MerchantId);
		PayConsumption cons = PayConsumption.initialize(virtualCard, payPwd, orgOrderNum, payGroupCode,
				DateUtil.fomatDate(new Date(), DateUtil.sdfTimes), orgOrderNum, tranAmt + "", "156", MerchantId);
		PayResult payConsumption = IPayAPI.consumption(cons);
		logger.info("=====================payConsumption"+payConsumption);
		if (!payConsumption.getRespCode().equals("0000")) {
			throw new ApplicationException(Rescode.FAIL, payConsumption.getMsgTxt());

		}
		return payConsumption;
	}



	@Override
	public PayResult updateUnPayConsumption(String virtualCard,String payMerchantCode, String payGroupCode, Long userId, Integer tranAmt,
			String orgOrderNum, String payPwd, String MerchantId) throws ApplicationException {
		
		
		 UnPayConsumption cons = UnPayConsumption.initialize(virtualCard,payMerchantCode, payGroupCode,
				 tranAmt+"", orgOrderNum, orgOrderNum,
	                DateUtils.getDateTimeString("yyyyMMddHHmmss"), payPwd,
	                UtilFun.createRandomNum(10),156+"");
		
		
//		IPayAPI.unPayConsumption(cons);
		
		return null;
	}



	@Override
	public Boolean updateRechargeNotify(Long memberId, Integer tranAmt,Integer sendtranAmt, String isWithdraw,String orderId)
			throws ApplicationException {
		Member member=memberMapper.queryGroup(memberId);
		if(member==null){
			return false;
		}
		Wallet wallet=walletMapper.selectByUserId(member.getUserId());
		switch (isWithdraw) {
		case "1":
			wallet.setCanBalance(tranAmt+wallet.getCanBalance());
			break;
		case "0":
			if(sendtranAmt!=null){
				//此处把赠送金额  给到用户
				PayResult payResult=accountBalance(member.getPayGroupCode(),member.getVirtualCard(), 
						sendtranAmt+"", isWithdraw, DateUtils.getDateTimeString("yyyyMMddHHmmss"));
				if (!PayBalanceResult.SUCCESS.equals(payResult.getRespCode())) {
					throw new ApplicationException(payResult.getMsgTxt());
		    	}
				wallet.setNocanBalance(tranAmt+sendtranAmt+wallet.getNocanBalance());
			}else{
				wallet.setNocanBalance(tranAmt+wallet.getNocanBalance());
			}
			break;
		default:
			break;
		}
		walletMapper.updateByPrimaryKeySelective(wallet);
		return true;
	}



	@Override
	public PayTransferResult updateConsumptionTransfer(String virtualCard, String toVirtualCard, String turnIntoUserName,
			String payGroupCode, Long userId,Long toUserId, Integer tranAmt, Integer fee, String orgOrderNum, String payPwd)
			throws ApplicationException {
		Integer tranAmtCount=tranAmt+fee;
		
		Wallet wallet=walletMapper.selectByUserId(userId);
		
		Date date=new Date();
		if(wallet==null){
			//查询余额
			PayBalanceResult payResult =getBalance(virtualCard, payGroupCode,false);
			Integer curBalA=Integer.valueOf(payResult.getCurBal());
			Integer curBalB=Integer.valueOf(payResult.getCurBalB());
			if(curBalB>=tranAmtCount){
				    logger.info ("直接扣B卡金额"); 
					Wallet walletDto=new Wallet();
					walletDto.setCanBalance(curBalA);
					walletDto.setCanBalanceLocked(0);
					walletDto.setNocanBalance(curBalB-tranAmtCount);
					walletDto.setNocanBalanceLocked(0);
					walletDto.setCanFreezeBalance(Integer.parseInt(payResult.getLockBal()));//支付平台可提现锁定金额
					walletDto.setNocanFreezeBalance(Integer.parseInt(payResult.getLockBalB()));//支付平台不可提现锁定金额
					walletDto.setUserId(userId);
					walletMapper.insertSelective(walletDto);
					
					WalletInfo walletInfo=new WalletInfo();
					walletInfo.setCanAmount(0);
					walletInfo.setNocanAmount(-tranAmtCount);
					walletInfo.setGmtCreate(date);
					walletInfo.setGmtEnd(date); 
					walletInfo.setUserId(userId);
					walletInfo.setVerify(1);//标记为结算
					walletInfo.setWalletId(walletDto.getId());
					
					walletInfoMapper.insertSelective(walletInfo);
						
					//不可提现转账
					addConsumptionTransfer(0, tranAmt, "0", toVirtualCard, payGroupCode, toUserId);
					
			}else{
				switch (curBalB) {
				case 0: 
					logger.info ("B卡金额为0  直接扣A卡金额"); 
					Wallet walletDto=new Wallet();
					walletDto.setCanBalance(curBalA-tranAmtCount);
					walletDto.setCanBalanceLocked(0);
					walletDto.setNocanBalance(0);
					walletDto.setNocanBalanceLocked(0);
					walletDto.setCanFreezeBalance(Integer.parseInt(payResult.getLockBal()));//支付平台可提现锁定金额
					walletDto.setNocanFreezeBalance(Integer.parseInt(payResult.getLockBalB()));//支付平台不可提现锁定金额
					walletDto.setUserId(userId);
					walletMapper.insertSelective(walletDto);
					
					WalletInfo walletInfo=new WalletInfo();
					walletInfo.setCanAmount(-tranAmtCount);
					walletInfo.setNocanAmount(0);
					walletInfo.setGmtCreate(date);
					walletInfo.setGmtEnd(date); 
					walletInfo.setUserId(userId);
					walletInfo.setVerify(1);//标记为结算
					walletInfo.setWalletId(walletDto.getId());
					walletInfoMapper.insertSelective(walletInfo);
					
					//可提现转账
					addConsumptionTransfer(tranAmt, 0, "1", toVirtualCard, payGroupCode, toUserId);
					
					break;
				default:
					logger.info ("扣完B卡金额 继续扣A卡金额"); 
					Wallet walletAB=new Wallet();
					walletAB.setCanBalance(curBalA+curBalB-tranAmtCount);
					walletAB.setCanBalanceLocked(0);
					walletAB.setNocanBalance(0);
					walletAB.setNocanBalanceLocked(0);
					walletAB.setCanFreezeBalance(Integer.parseInt(payResult.getLockBal()));//支付平台可提现锁定金额
					walletAB.setNocanFreezeBalance(Integer.parseInt(payResult.getLockBalB()));//支付平台不可提现锁定金额
					walletAB.setUserId(userId);
					walletMapper.insertSelective(walletAB);
					
					WalletInfo walletInfoAB=new WalletInfo();
					walletInfoAB.setCanAmount(-(tranAmtCount-curBalB));// 消费金额=消费金额-B卡金额
					walletInfoAB.setNocanAmount(-curBalB);
					walletInfoAB.setGmtCreate(date);
					walletInfoAB.setGmtEnd(date); 
					walletInfoAB.setUserId(userId);
					walletInfoAB.setVerify(1);//标记为结算
					walletInfoAB.setWalletId(walletAB.getId());
					walletInfoMapper.insertSelective(walletInfoAB);
					
					//混合转账 
					addConsumptionTransfer(tranAmt-curBalB, curBalB, "2", toVirtualCard, payGroupCode, toUserId);
					break;
				}
				
			}
			
		}else{
					if(wallet.getNocanBalance()>=tranAmtCount){//
						logger.info ("直接扣B卡金额"); 
						wallet.setNocanBalance(wallet.getNocanBalance()-tranAmtCount);
						walletMapper.updateByPrimaryKeySelective(wallet);
						
						WalletInfo walletInfo=new WalletInfo();
						walletInfo.setCanAmount(0);
						walletInfo.setNocanAmount(-tranAmtCount);
						walletInfo.setGmtCreate(date);
						walletInfo.setGmtEnd(date); 
						walletInfo.setUserId(userId);
						walletInfo.setVerify(1);//标记为结算
						walletInfo.setWalletId(wallet.getId());
						
						walletInfoMapper.insertSelective(walletInfo);
							
						//不可提现转账
						addConsumptionTransfer(0, tranAmt, "0", toVirtualCard, payGroupCode, toUserId);
						
					}else{
						//B卡余额为0
						switch (wallet.getNocanBalance()) {
						case 0: 
							logger.info ("B卡金额为0  直接扣A卡金额"); 
							Integer Balance1=wallet.getCanBalance();
							wallet.setCanBalance(Balance1-tranAmtCount);
							walletMapper.updateByPrimaryKeySelective(wallet);
							WalletInfo walletInfo=new WalletInfo();
							walletInfo.setCanAmount(-tranAmtCount);
							walletInfo.setNocanAmount(0);
							walletInfo.setGmtCreate(date);
							walletInfo.setGmtEnd(date); 
							walletInfo.setUserId(userId);
							walletInfo.setVerify(1);//标记为结算
							walletInfo.setWalletId(wallet.getId());
							walletInfoMapper.insertSelective(walletInfo);
							
							//可提现转账
							addConsumptionTransfer(tranAmt, 0, "1", toVirtualCard, payGroupCode, toUserId);
							break;
						default:
							logger.info ("扣完B卡金额 继续扣A卡金额"); 
							Integer BalanceA=wallet.getCanBalance();
							Integer BalanceB=wallet.getNocanBalance();
							wallet.setCanBalance(BalanceA+BalanceB-tranAmtCount);
							wallet.setNocanBalance(0);
							WalletInfo walletInfoAB=new WalletInfo();
							walletInfoAB.setCanAmount(-(tranAmtCount-BalanceB));// 消费金额=消费金额-B卡金额
							walletInfoAB.setNocanAmount(-BalanceB);
							walletInfoAB.setGmtCreate(date);
							walletInfoAB.setGmtEnd(date); 
							walletInfoAB.setUserId(userId);
							walletInfoAB.setVerify(1);//标记为结算
							walletInfoAB.setWalletId(wallet.getId());
							walletMapper.updateByPrimaryKeySelective(wallet);
							walletInfoMapper.insertSelective(walletInfoAB);
							
							//混合转账 
							addConsumptionTransfer(tranAmt-BalanceB, BalanceB, "2", toVirtualCard, payGroupCode, toUserId);
							break;
						}
				}
		}
			PayTransfer payTransfer = PayTransfer.initialize(virtualCard,payPwd,payGroupCode,
					orgOrderNum,toVirtualCard,DateUtils.getDateTimeString("yyyyMMddHHmmss"),
					orgOrderNum,tranAmt+"","156",turnIntoUserName,fee+"");
			PayTransferResult payTransferResult = IPayAPI.consumptionTransfer(payTransfer);
			if(!payTransferResult.getRespCode().equals("0000")) {
				throw new ApplicationException(Rescode.FAIL,payTransferResult.getMsgTxt());
			}
			return payTransferResult; 
	}

	
	
	
	
	/**
	 * 转账
	 * @param tranAmt  可提现
	 * @param notranAmt  不可提现
	 * @param isWithdraw  1 表示全部可提现  0表示全部不可提现   2表示两者都有
	 * @param virtualCard
	 * @param payGroupCode
	 * @param userId
	 * @return
	 * @throws ApplicationException
	 */
	public Boolean addConsumptionTransfer(Integer tranAmt,Integer notranAmt, String isWithdraw,String virtualCard,String payGroupCode,Long userId)
			throws ApplicationException{
		Wallet wallet=walletMapper.selectByUserId(userId);
		Date date=new Date();
		if(wallet==null){
				PayBalanceResult payResult =getBalance(virtualCard, payGroupCode,false);
				Wallet walletDto=new Wallet();
				
				walletDto.setUserId(userId);
				walletDto.setCanBalanceLocked(0);
				walletDto.setNocanBalanceLocked(0);
				walletDto.setCanFreezeBalance(Integer.parseInt(payResult.getLockBal()));//支付平台可提现锁定金额
				walletDto.setNocanFreezeBalance(Integer.parseInt(payResult.getLockBalB()));//支付平台不可提现锁定金额
				
				WalletInfo walletInfo=new WalletInfo();
				switch (isWithdraw) {
				case "1":
					walletDto.setCanBalance(Integer.parseInt(payResult.getCurBal())+tranAmt);
					walletDto.setNocanBalance(Integer.parseInt(payResult.getCurBalB()));
					
					walletInfo.setCanAmount(tranAmt);
					walletInfo.setNocanAmount(0);
					break;
				case "0":
					walletDto.setCanBalance(Integer.parseInt(payResult.getCurBal()));//可提现金额
					walletDto.setNocanBalance(Integer.parseInt(payResult.getCurBalB())+notranAmt);//不可提现金额
					
					walletInfo.setCanAmount(0);
					walletInfo.setNocanAmount(notranAmt);
					break;
				case "2":
					walletDto.setCanBalance(Integer.parseInt(payResult.getCurBal())+tranAmt);//可提现金额
					walletDto.setNocanBalance(Integer.parseInt(payResult.getCurBalB())+notranAmt);//不可提现金额
					
					walletInfo.setCanAmount(tranAmt);
					walletInfo.setNocanAmount(notranAmt);
					break;
				}
				
				
				walletInfo.setGmtEnd(date);
				walletInfo.setVerify(1);//标记为结算
				
				walletInfo.setGmtCreate(date);
				walletInfo.setUserId(userId);
				walletMapper.insertSelective(walletDto);
				walletInfo.setWalletId(walletDto.getId());
				walletInfoMapper.insertSelective(walletInfo);
				
		}else{
			//本地缓存了余额  直接做加减处理  为了保持一致性 1天内做一次查询余额比较一致性
			WalletInfo walletInfo=new WalletInfo();
				
			switch (isWithdraw) {
			case "1":
				walletInfo.setCanAmount(Integer.valueOf(tranAmt));
				walletInfo.setNocanAmount(0);
				//可提现金额直接累加
				wallet.setCanBalance(wallet.getCanBalance()+Integer.valueOf(tranAmt));
				break;
			case "0":
				walletInfo.setCanAmount(0);
				walletInfo.setNocanAmount(notranAmt);
				//不可提现金额直接累加
				wallet.setNocanBalance(wallet.getNocanBalance()+notranAmt);//不可提现金额
				break;
				
			case "2":
				walletInfo.setCanAmount(tranAmt);
				walletInfo.setNocanAmount(notranAmt);
				
				//可提现金额直接累加
				wallet.setCanBalance(wallet.getCanBalance()+Integer.valueOf(tranAmt));
				//不可提现金额直接累加
				wallet.setNocanBalance(wallet.getNocanBalance()+notranAmt);//不可提现金额
				break;	
			}
			walletInfo.setGmtEnd(date);
			walletInfo.setVerify(1);//标记为已结算
			
			walletInfo.setGmtCreate(date);
			walletInfo.setUserId(userId);
			walletInfo.setWalletId(wallet.getId());
			
			walletMapper.updateByPrimaryKeySelective(wallet);
			walletInfoMapper.insertSelective(walletInfo);
		}
		return true;
	}



	@Override
	public PayWithdrawalResult updateBankWithdrawal(String virtualCard, String payGroupCode, Long userId, Integer tranAmt,
			String orderId, String payPwd, String cardNum, String bankIntegral, String idName, String issuerBankName,Integer fee) throws ApplicationException {
		Wallet wallet=walletMapper.selectByUserId(userId);
		Integer tranAmtCount=tranAmt+fee;
		Date date=new Date();
		if(wallet==null){
			//查询余额
			PayBalanceResult payResult =getBalance(virtualCard, payGroupCode,false);
			Integer curBalA=Integer.valueOf(payResult.getCurBal());
			Integer curBalB=Integer.valueOf(payResult.getCurBalB());
			
			Wallet walletDto=new Wallet();
			walletDto.setCanBalance(curBalA-tranAmtCount);
			walletDto.setCanBalanceLocked(0);
			walletDto.setNocanBalance(curBalB);
			walletDto.setNocanBalanceLocked(0);
			walletDto.setUserId(userId);
			walletDto.setCanFreezeBalance(Integer.parseInt(payResult.getLockBal())+tranAmtCount);//支付平台可提现锁定金额
			walletDto.setNocanFreezeBalance(Integer.parseInt(payResult.getLockBalB()));//支付平台不可提现锁定金额
			walletMapper.insertSelective(walletDto);
			
			WalletInfo walletInfo=new WalletInfo();
			walletInfo.setCanAmount(-tranAmtCount);
			walletInfo.setNocanAmount(0);
			walletInfo.setGmtCreate(date);
			walletInfo.setGmtEnd(date); 
			walletInfo.setUserId(userId);
			walletInfo.setVerify(2);//标记为待确认
			walletInfo.setWalletId(walletDto.getId());
			walletInfo.setOrderId(orderId); 
			walletInfoMapper.insertSelective(walletInfo);
			
		}else{
			wallet.setCanBalance(wallet.getCanBalance()-tranAmtCount);
			wallet.setCanFreezeBalance(wallet.getCanFreezeBalance()+tranAmtCount);//提现锁定金额累加
			walletMapper.updateByPrimaryKeySelective(wallet);
			WalletInfo walletInfo=new WalletInfo();
			walletInfo.setCanAmount(-tranAmtCount);
			walletInfo.setNocanAmount(0);
			walletInfo.setGmtCreate(date);
			walletInfo.setGmtEnd(date); 
			walletInfo.setUserId(userId);
			walletInfo.setVerify(2);//标记为待确认
			walletInfo.setWalletId(wallet.getId());
			walletInfo.setOrderId(orderId); 
			walletInfoMapper.insertSelective(walletInfo);
			
		}
		
		PayWithdrawalBank payWithdrawalBank = PayWithdrawalBank.initialize(virtualCard, payGroupCode, null,
				orderId, tranAmt+"", payPwd, "PERSONAL", cardNum, bankIntegral, bankIntegral, null,
				idName, "22", issuerBankName,fee+"");
		PayWithdrawalResult result = IPayAPI.bankWithdrawal(payWithdrawalBank);
		if(result==null || result.getVerificationStatus().byteValue()==0x00){
			logger.info(PayWithdrawalResult.getNotNullMsgTxt(result, "提现申请提交失败,通信异常"));
			throw new ApplicationException(Rescode.FAIL, "提现申请提交失败,通信异常");
		}
		return result;
	}
	
	
	
	
	@Override
	public PayTransferResult updateMerchantWithsDraw(String virtualCard, String payGroupCode, Long userId,
			Integer tranAmt, String orgOrderNum) throws ApplicationException {
		
		Wallet wallet=walletMapper.selectByUserId(userId);
		Date date=new Date();
		if(wallet==null){
			//查询余额
			PayBalanceResult payResult =getBalance(virtualCard, payGroupCode,true);
			Integer curBalA=Integer.valueOf(payResult.getCurBal());
			Integer curBalB=Integer.valueOf(payResult.getCurBalB());
			
			Wallet walletDto=new Wallet();
			walletDto.setCanBalance(curBalA-tranAmt);
			walletDto.setCanBalanceLocked(0);
			walletDto.setNocanBalance(curBalB);
			walletDto.setNocanBalanceLocked(0);
			walletDto.setUserId(userId);
			walletDto.setCanFreezeBalance(Integer.parseInt(payResult.getLockBal())+tranAmt);//支付平台可提现锁定金额
			walletDto.setNocanFreezeBalance(Integer.parseInt(payResult.getLockBalB()));//支付平台不可提现锁定金额
			walletMapper.insertSelective(walletDto);
			
			WalletInfo walletInfo=new WalletInfo();
			walletInfo.setCanAmount(-tranAmt);
			walletInfo.setNocanAmount(0);
			walletInfo.setGmtCreate(date);
			walletInfo.setGmtEnd(date); 
			walletInfo.setUserId(userId);
			walletInfo.setVerify(2);//标记为待确认
			walletInfo.setWalletId(walletDto.getId());
			walletInfo.setOrderId(orgOrderNum); 
			
			walletInfoMapper.insertSelective(walletInfo);
			
		}else{
			Integer BalanceA=wallet.getCanBalance();
			wallet.setCanBalance(BalanceA-tranAmt);
			wallet.setCanFreezeBalance(wallet.getCanFreezeBalance()+tranAmt);
			walletMapper.updateByPrimaryKeySelective(wallet);
			WalletInfo walletInfo=new WalletInfo();
			walletInfo.setCanAmount(-tranAmt);
			walletInfo.setNocanAmount(0);
			walletInfo.setGmtCreate(date);
			walletInfo.setGmtEnd(date); 
			walletInfo.setUserId(userId);
			walletInfo.setVerify(2);//标记为待确认
			walletInfo.setWalletId(wallet.getId());
			walletInfo.setOrderId(orgOrderNum); 
			walletInfoMapper.insertSelective(walletInfo);
			
		}
		 MerchantWithsDraw merchantWithsDraw=MerchantWithsDraw.initialize(payGroupCode,orgOrderNum,tranAmt.toString(),virtualCard);
	     PayTransferResult payResult=IPayAPI.merchantWithsDraw(merchantWithsDraw);
	     if(!PayResult.SUCCESS.equals(payResult.getRespCode())){
	         throw new ApplicationException(payResult.getRespCode(),payResult.getMsgTxt());
	     }
		return payResult;
	}
	
	
	



	@Override
	public Boolean updateBankWithdrawalNotify(String orderId,Long payerId,Boolean flag,Integer type) throws ApplicationException {
		if(type==null){
			return false;
		}
		
		Long userId= null;
		switch (type) {
		case 1:
			Member member=memberMapper.selectByPrimaryKey(payerId);
			userId=member.getUserId();
			break;
		case 2:
			Agent agent=agentMapper.selectByPrimaryKey(payerId);
			userId=agent.getUserId();
			break;
		case 3:
			Shop shop=shopMapper.selectByPrimaryKey(payerId);
			userId=shop.getUserId();
			break;
		default:
			break;
		}
		
		
		Wallet wallet=walletMapper.selectByUserId(userId);
		if(wallet==null){
			return false;
		}
		
		WalletInfo walletInfo=walletInfoMapper.selectByOrderId(orderId);
		if(walletInfo==null){
			return false;
		}
		walletInfo.setVerify(1);//标记为确认
		
		
		//提现金额
		Integer withdrawAmount=walletInfo.getCanAmount();
		
		if(withdrawAmount<0){
			withdrawAmount=-(withdrawAmount);
		}
		
		if(flag){
			//释放锁定金额
			wallet.setCanFreezeBalance(wallet.getCanFreezeBalance()-withdrawAmount);
		}else{
			//释放锁定金额
			wallet.setCanFreezeBalance(wallet.getCanFreezeBalance()-withdrawAmount);
			//提现失败 把余额加回去
			wallet.setCanBalance(wallet.getCanBalance()+withdrawAmount);
		}
		walletMapper.updateByPrimaryKeySelective(wallet);
		walletInfoMapper.updateByPrimaryKeySelective(walletInfo);
		return true;
		
	}



	@Override
	public PayResult updateWarrantWithdrawal(String virtualCard, String payGroupCode, Long userId,
			Integer tranAmt, String orderId, String payPwd, Integer fee)
			throws ApplicationException {
		Wallet wallet=walletMapper.selectByUserId(userId);
		Integer tranAmtCount=tranAmt+fee;
		Date date=new Date();
		if(wallet==null){
			//查询余额
			PayBalanceResult payResult =getBalance(virtualCard, payGroupCode,false);
			Integer curBalA=Integer.valueOf(payResult.getCurBal());
			Integer curBalB=Integer.valueOf(payResult.getCurBalB());
			
			Integer LockBalA=Integer.valueOf(payResult.getLockBal());
			
			Wallet walletDto=new Wallet();
			walletDto.setCanBalance(curBalA-tranAmtCount);
			walletDto.setCanBalanceLocked(LockBalA);
			walletDto.setNocanBalance(curBalB);
			walletDto.setNocanBalanceLocked(0);
			walletDto.setUserId(userId);
			walletDto.setCanFreezeBalance(Integer.parseInt(payResult.getLockBal())+tranAmtCount);//支付平台可提现锁定金额
			walletDto.setNocanFreezeBalance(Integer.parseInt(payResult.getLockBalB()));//支付平台不可提现锁定金额
			walletMapper.insertSelective(walletDto);
			
			WalletInfo walletInfo=new WalletInfo();
			walletInfo.setCanAmount(-tranAmtCount);
			walletInfo.setNocanAmount(0);
			walletInfo.setGmtCreate(date);
			walletInfo.setGmtEnd(date); 
			walletInfo.setUserId(userId);
			walletInfo.setVerify(2);//标记为待确认
			walletInfo.setWalletId(walletDto.getId());
			walletInfo.setOrderId(orderId); 
			walletInfoMapper.insertSelective(walletInfo);
			
		}else{
			Integer BalanceA=wallet.getCanBalance();
			wallet.setCanBalance(BalanceA-tranAmtCount);
			wallet.setCanFreezeBalance(wallet.getCanFreezeBalance()+tranAmtCount);//支付平台可提现锁定金额
			walletMapper.updateByPrimaryKeySelective(wallet);
			WalletInfo walletInfo=new WalletInfo();
			walletInfo.setCanAmount(-tranAmtCount);
			walletInfo.setNocanAmount(0);
			walletInfo.setGmtCreate(date);
			walletInfo.setGmtEnd(date); 
			walletInfo.setUserId(userId);
			walletInfo.setVerify(2);//标记为待确认
			walletInfo.setWalletId(wallet.getId());
			walletInfo.setOrderId(orderId); 
			walletInfoMapper.insertSelective(walletInfo);
		}
		
		 String sysTraceNum = UtilFun.createRandomNum(10);
		 String orgTranDateTime = DateUtils.getDateTimeString("yyyyMMddHHmmss");
		
		 WarrantDrawRequest pw= WarrantDrawRequest.initialize( virtualCard,  payGroupCode,  tranAmt+"",  null,
				 orderId,  orgTranDateTime,  payPwd,  sysTraceNum,  "156",
                 "2",null);
         PayResult payResult=IPayAPI.WarrantWithdrawal(pw);
         if(!PayResult.SUCCESS.equals(payResult.getRespCode())){
             throw new ApplicationException(payResult.getRespCode(),payResult.getMsgTxt());
         }
		
		return payResult;
	}

	@Override
	public PayResult updateWallInforPosWallPay(String virtualCard, String payGroupCode, Long userId, Integer realAmount, String orderNo) throws ApplicationException {
		Wallet wallet=walletMapper.selectByUserId(userId);
		Date date=new Date();
		if(wallet==null){
			//查询余额
			PayBalanceResult payResult =getBalance(virtualCard, payGroupCode,false);
			Integer curBalA=Integer.valueOf(payResult.getCurBal());
			Integer curBalB=Integer.valueOf(payResult.getCurBalB());
			if(curBalB>=realAmount){
				logger.info ("直接扣B卡金额");
				Wallet walletDto=new Wallet();
				walletDto.setCanBalance(curBalA);
				walletDto.setCanBalanceLocked(0);
				walletDto.setNocanBalance(curBalB-realAmount);
				walletDto.setNocanBalanceLocked(0);
				walletDto.setCanFreezeBalance(Integer.parseInt(payResult.getLockBal()));//支付平台可提现锁定金额
				walletDto.setNocanFreezeBalance(Integer.parseInt(payResult.getLockBalB()));//支付平台不可提现锁定金额
				walletDto.setUserId(userId);
				walletMapper.insertSelective(walletDto);

				WalletInfo walletInfo=new WalletInfo();
				walletInfo.setCanAmount(0);
				walletInfo.setNocanAmount(-realAmount);
				walletInfo.setGmtCreate(date);
				walletInfo.setGmtEnd(date);
				walletInfo.setUserId(userId);
				walletInfo.setVerify(1);//标记为结算
				walletInfo.setWalletId(walletDto.getId());
				walletInfo.setOrderId(orderNo);

				walletInfoMapper.insertSelective(walletInfo);

				//不可提现转账
//				addConsumptionTransfer(0, tranAmt, "0", toVirtualCard, payGroupCode, toUserId);

			}else{
				switch (curBalB) {
					case 0:
						logger.info ("B卡金额为0  直接扣A卡金额");
						Wallet walletDto=new Wallet();
						walletDto.setCanBalance(curBalA-realAmount);
						walletDto.setCanBalanceLocked(0);
						walletDto.setNocanBalance(0);
						walletDto.setNocanBalanceLocked(0);
						walletDto.setCanFreezeBalance(Integer.parseInt(payResult.getLockBal()));//支付平台可提现锁定金额
						walletDto.setNocanFreezeBalance(Integer.parseInt(payResult.getLockBalB()));//支付平台不可提现锁定金额
						walletDto.setUserId(userId);
						walletMapper.insertSelective(walletDto);

						WalletInfo walletInfo=new WalletInfo();
						walletInfo.setCanAmount(-realAmount);
						walletInfo.setNocanAmount(0);
						walletInfo.setGmtCreate(date);
						walletInfo.setGmtEnd(date);
						walletInfo.setUserId(userId);
						walletInfo.setVerify(1);//标记为结算
						walletInfo.setWalletId(walletDto.getId());
						walletInfo.setOrderId(orderNo);
						walletInfoMapper.insertSelective(walletInfo);

						//可提现转账
//						addConsumptionTransfer(tranAmt, 0, "1", toVirtualCard, payGroupCode, toUserId);

						break;
					default:
						logger.info ("扣完B卡金额 继续扣A卡金额");
						Wallet walletAB=new Wallet();
						walletAB.setCanBalance(curBalA+curBalB-realAmount);
						walletAB.setCanBalanceLocked(0);
						walletAB.setNocanBalance(0);
						walletAB.setNocanBalanceLocked(0);
						walletAB.setCanFreezeBalance(Integer.parseInt(payResult.getLockBal()));//支付平台可提现锁定金额
						walletAB.setNocanFreezeBalance(Integer.parseInt(payResult.getLockBalB()));//支付平台不可提现锁定金额
						walletAB.setUserId(userId);
						walletMapper.insertSelective(walletAB);

						WalletInfo walletInfoAB=new WalletInfo();
						walletInfoAB.setCanAmount(-(realAmount-curBalB));// 消费金额=消费金额-B卡金额
						walletInfoAB.setNocanAmount(-curBalB);
						walletInfoAB.setGmtCreate(date);
						walletInfoAB.setGmtEnd(date);
						walletInfoAB.setUserId(userId);
						walletInfoAB.setVerify(1);//标记为结算
						walletInfoAB.setWalletId(walletAB.getId());
						walletInfoAB.setOrderId(orderNo);
						walletInfoMapper.insertSelective(walletInfoAB);

						//混合转账
//						addConsumptionTransfer(tranAmt-curBalB, curBalB, "2", toVirtualCard, payGroupCode, toUserId);
						break;
				}

			}

		}else{
			if(wallet.getNocanBalance()>=realAmount){//
				logger.info ("直接扣B卡金额");
				wallet.setNocanBalance(wallet.getNocanBalance()-realAmount);
				walletMapper.updateByPrimaryKeySelective(wallet);

				WalletInfo walletInfo=new WalletInfo();
				walletInfo.setCanAmount(0);
				walletInfo.setNocanAmount(-realAmount);
				walletInfo.setGmtCreate(date);
				walletInfo.setGmtEnd(date);
				walletInfo.setUserId(userId);
				walletInfo.setVerify(1);//标记为结算
				walletInfo.setWalletId(wallet.getId());
				walletInfo.setOrderId(orderNo);
				walletInfoMapper.insertSelective(walletInfo);

				//不可提现转账
//				addConsumptionTransfer(0, tranAmt, "0", toVirtualCard, payGroupCode, toUserId);

			}else{
				//B卡余额为0
				switch (wallet.getNocanBalance()) {
					case 0:
						logger.info ("B卡金额为0  直接扣A卡金额");
						Integer Balance1=wallet.getCanBalance();
						wallet.setCanBalance(Balance1-realAmount);
						walletMapper.updateByPrimaryKeySelective(wallet);
						WalletInfo walletInfo=new WalletInfo();
						walletInfo.setCanAmount(-realAmount);
						walletInfo.setNocanAmount(0);
						walletInfo.setGmtCreate(date);
						walletInfo.setGmtEnd(date);
						walletInfo.setUserId(userId);
						walletInfo.setVerify(1);//标记为结算
						walletInfo.setWalletId(wallet.getId());
						walletInfo.setOrderId(orderNo);
						walletInfoMapper.insertSelective(walletInfo);

						//可提现转账
//						addConsumptionTransfer(tranAmt, 0, "1", toVirtualCard, payGroupCode, toUserId);
						break;
					default:
						logger.info ("扣完B卡金额 继续扣A卡金额");
						Integer BalanceA=wallet.getCanBalance();
						Integer BalanceB=wallet.getNocanBalance();
						wallet.setCanBalance(BalanceA+BalanceB-realAmount);
						wallet.setNocanBalance(0);
						WalletInfo walletInfoAB=new WalletInfo();
						walletInfoAB.setCanAmount(-(realAmount-BalanceB));// 消费金额=消费金额-B卡金额
						walletInfoAB.setNocanAmount(-BalanceB);
						walletInfoAB.setGmtCreate(date);
						walletInfoAB.setGmtEnd(date);
						walletInfoAB.setUserId(userId);
						walletInfoAB.setVerify(1);//标记为结算
						walletInfoAB.setWalletId(wallet.getId());
						walletInfoAB.setOrderId(orderNo);
						walletMapper.updateByPrimaryKeySelective(wallet);
						walletInfoMapper.insertSelective(walletInfoAB);

						//混合转账
//						addConsumptionTransfer(tranAmt-BalanceB, BalanceB, "2", toVirtualCard, payGroupCode, toUserId);
						break;
				}
			}
		}
//		MerchantWithsDraw merchantWithsDraw=MerchantWithsDraw.initialize(payGroupCode,orgOrderNum,tranAmt.toString(),virtualCard);
//		PayTransferResult payResult=IPayAPI.merchantWithsDraw(merchantWithsDraw);
//		if(!PayResult.SUCCESS.equals(payResult.getRespCode())){
//			throw new ApplicationException(payResult.getRespCode(),payResult.getMsgTxt());
//		}
//		return payResult;
		return null;
	}





}
